package com.beyond.core.handler;

import com.beyond.core.common.EscapeTool;
import com.beyond.core.entity.AisleFaultData;
import com.beyond.core.entity.FaultRadarData;
import com.beyond.core.service.ProtocolService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FaultQueryHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        ByteBuf content = datagramPacket.content();
        byte[] bytes=new byte[content.readableBytes()];
        content.readBytes(bytes);

        //处理转义字符
        byte[] responseData = EscapeTool.reverseEscapeData(bytes);
        byte[] cutMsg = new byte[responseData.length - 3]; //剪除3个字节 协议头，尾，校验和
        for (int i = 0; i < cutMsg.length; i++) {
            cutMsg[i] = bytes[i + 1];
        }
        //处理数据
        //检测通道数
        int detectionAisleCountL = cutMsg[4] & 0xff;

        //封装每个通道是否故障
        List<AisleFaultData> aisleFaultDataList = new ArrayList<>();
        for (int i = 0; i < detectionAisleCountL; i++) {
            byte[] faultData = new byte[3];
            for (int j = 0; j < 3; j++) {
                faultData[j] = cutMsg[5 + i * 3 + j];
            }
            //检测通道号
            int detectionAisleNumL = faultData[0] & 0xff;

            //通道状态 0:通道正常； 1:通道故障
            int aisleStatusL = faultData[1] & 0xff;

            //故障类型 1：其他异常。（目前检测器暂无异常检测，待后续扩展）
            int faultTypeL = faultData[2] & 0xff;

            AisleFaultData aisleFaultData = new AisleFaultData();
            aisleFaultData.setDetectionAisleNum(detectionAisleNumL);
            aisleFaultData.setAisleStatus(aisleStatusL);
            aisleFaultData.setFaultType(faultTypeL);
            aisleFaultDataList.add(aisleFaultData);
        }
        FaultRadarData faultRadarData = new FaultRadarData();
        faultRadarData.setDetectionAisleCount(detectionAisleCountL);
        faultRadarData.setAisleFaultDataList(aisleFaultDataList);

        try {
            String jsonStr = mapper.writeValueAsString(faultRadarData);
            log.info(jsonStr);
            //TODO 等待入库或者缓存数据 备用
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        cause.printStackTrace();
        log.debug("问询故障通道异常");
        ctx.close();
    }
}
